/**
 * 
 */
package com.munoor.dalai.server.api;

import javax.persistence.EntityManager;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import com.munoor.dalai.server.model.Company;
import com.munoor.dalai.server.model.EMFService;
import com.munoor.dalai.server.model.wrappers.WrappedCompany;
import com.sun.jersey.api.NotFoundException;


/**
 * @author Osho Ilamah
 * @since  version 1.0 (07 April 2011)
 */
public class CompanyResource {
	@Context
	UriInfo uriInfo;
	@Context
	Request request;
	Long id;
	
	public CompanyResource(UriInfo uriInfo, Request request, Long id) {
		this.uriInfo = uriInfo;
		this.request = request;
		this.id = id;
	}
	
	@GET
	@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
	public WrappedCompany readCompany() {
		EntityManager em = EMFService.get().createEntityManager();
		try {
			return new WrappedCompany(((Company) em.createNamedQuery("Companies.findByCompanyId").setParameter("companyId", id).getSingleResult()));
		} catch (Exception e) {
			throw new NotFoundException("Not Found");
		} finally {
			em.close();
		}
	}
	@PUT
	@Consumes(MediaType.APPLICATION_JSON)
	public Response updateCompany(WrappedCompany postData) {
		EntityManager em = EMFService.get().createEntityManager();
		Company company = null;
		try {
			company = postData.unmarshall();
			company.setCompanyId(id);
			em.merge(company);
			return Response.noContent().build();
		} catch (Exception e) {
			return Response.serverError().build();
		}finally{
			em.close();
		}	
	}

	@DELETE
	public Response deleteCompany() {
		EntityManager em = EMFService.get().createEntityManager();
		Company company = null;
		try {
			company = (Company) em.createNamedQuery("Companies.findByCompanyId").setParameter("companyId", id).getSingleResult();
			em.remove(company);
			return Response.noContent().build();
		} catch (Exception e) {
			throw new NotFoundException("Not Found");
		}finally{
			em.close();
		}
	}
	
}
